package com.example.taobaolianmeng.presenter.impl;

import android.util.Log;

import com.example.taobaolianmeng.R;
import com.example.taobaolianmeng.model.Api;
import com.example.taobaolianmeng.model.domain.Categories;
import com.example.taobaolianmeng.presenter.IHomePresenter;
import com.example.taobaolianmeng.utils.RetrofitManager;
import com.example.taobaolianmeng.view.IHomeCallBack;

import java.net.HttpURLConnection;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class HomePresenterImpl implements IHomePresenter {

    private static final String TAG = "HomePresenterImpl";
    private IHomeCallBack mCallback = null;

    @Override
    public void getCategories() {
        if (mCallback !=null) {
            mCallback.onLoading();
        }
        //加载数据
        Retrofit retrofit = RetrofitManager.getInstance().getRetrofit();
        Api api = retrofit.create(Api.class);
        Call<Categories> task = api.getCategories();
        task.enqueue(new Callback<Categories>() {
            @Override
            public void onResponse(Call<Categories> call, Response<Categories> response) {
                //success
                int code = response.code();
                if(code == HttpURLConnection.HTTP_OK){
                    Categories categories = response.body();
//                    Log.d(TAG,"res->"+categories.toString());
                    if (mCallback != null) {
                        if(categories ==null || categories.getData().size() ==0){
                            mCallback.onEmpty();
                        }else{
                            mCallback.onEmpty();
                            mCallback.onCategoriesLoad(categories);
                        }
                    }
                }else{
                    if(mCallback !=null){
                        mCallback.onNetworkError();
                    }
                }
            }

            @Override
            public void onFailure(Call<Categories> call, Throwable t) {
                //error
                Log.d(TAG,"error"+t.toString());
                if(mCallback !=null){
                    mCallback.onNetworkError();
                }
            }
        });

    }

    @Override
    public void registerViewCallback(IHomeCallBack callBack) {
        this.mCallback =callBack;

    }

    @Override
    public void unregisterViewCallback(IHomeCallBack callBack) {
        mCallback = null;
    }
}
